#include "response_listener.h"
#include "../event_loop/event_loop.h"
#include "../common/collection_type.h"
ResponseListener::ResponseListener( std::shared_ptr<grpc::CompletionQueue> cq):cq_(cq)
{
	//std::list<std::shared_ptr<Collection>>
}

ResponseListener::~ResponseListener()
{
	//cq_->Shutdown();
	thread.get();
}

void ResponseListener::run()
{
	void* got_tag;
	bool ok = false;
	//lock.lock();
	while (cq_->Next(&got_tag, &ok)) {
		auto testptr = static_cast<CallData<DataExchange::CollectionsResponse>*>(got_tag);

		GPR_ASSERT(ok);
		if (!testptr->status.ok()) {
			std::cout << "RPC failed" << std::endl;
			delete testptr->selfptr;
			continue;
		}

		switch (testptr->tablename) {
		case DataExchange::Collections: {
			//auto ptr = static_cast<CallData<DataExchange::CollectionsResponse>*>(got_tag);
			testptr->event->setPayload(testptr->geter());
			testptr->event->setDone();
			EventLoop::replyEvent(std::move(testptr->event));
			delete testptr->selfptr;
			break;
		}
		case DataExchange::Strategies: {
			auto ptr = static_cast<CallData<DataExchange::StrategiesResponse>*>(got_tag);
			ptr->event->setPayload(ptr->geter());
			testptr->event->setDone();
			EventLoop::replyEvent(std::move(ptr->event));
			delete ptr->selfptr;
			break;
		}
		case DataExchange::GlobalFactors: {
			auto ptr = static_cast<CallData<DataExchange::FactorsResponse>*>(got_tag);
			ptr->event->setPayload(ptr->geter());
			testptr->event->setDone();
			EventLoop::replyEvent(std::move(ptr->event));
			delete ptr->selfptr;
			break;
		}
		case DataExchange::GlobalContracts: {
			auto ptr = static_cast<CallData<DataExchange::ContractsResponse>*>(got_tag);
			ptr->event->setPayload(ptr->geter());
			testptr->event->setDone();
			EventLoop::replyEvent(std::move(ptr->event));
			delete ptr->selfptr;
			break;
		}
		default:
			break;

		}


		

	}

	//lock.unlock();
}

void ResponseListener::start()
{
	thread = std::async(std::launch::async ,&ResponseListener::run,this);
}

void ResponseListener::stop()
{
	cq_->Shutdown();
}


